package com.sinochem.yunlian.ship.base.rest;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.sinochem.yunlian.ship.base.biz.BsMaterialCategoryBiz;
import com.sinochem.yunlian.ship.base.biz.BsPortBiz;
import com.sinochem.yunlian.ship.base.entity.BsMaterialCategory;
import com.sinochem.yunlian.ship.base.entity.BsPort;
import com.sinochem.yunlian.ship.base.vo.request.MaterialCategoryForm;
import com.sinochem.yunlian.ship.base.vo.response.MaterialCategoryVo;
import com.sinochem.yunlian.ship.base.vo.response.RespMaterialCategoryLeveVo;
import com.sinochem.yunlian.ship.common.annotation.IgnoreToken;
import com.sinochem.yunlian.ship.common.constant.DisableStatus;
import com.sinochem.yunlian.ship.common.constant.RedisKey;
import com.sinochem.yunlian.ship.common.msg.RestResponse;
import com.sinochem.yunlian.ship.common.rest.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author panyanan
 * @date 2017-11-20 21:02
 *
 * */
@IgnoreToken
@RestController
@RequestMapping("materialCategory")
public class BsMaterialCategoryController extends BaseController<BsPortBiz,BsPort> {

    @Autowired
    private BsMaterialCategoryBiz bsMaterialCategoryBiz;
    @Autowired
    private RedisTemplate redisTemplate;
    
    private final Logger log = LoggerFactory.getLogger(BsMaterialCategoryController.class);

    /**
     * 查找港口
     * */
    @RequestMapping(value = "/findAll/anon", method = RequestMethod.GET)
    public RestResponse findPorts(){
        RestResponse result = new RestResponse();
        List<MaterialCategoryVo> listVo = new ArrayList<>();

        //查询所有已经启用的货品种类信息 目前只有两级后期改为递归
        if (redisTemplate.hasKey(RedisKey.KEY_MATERIAL_CATEGORY_ALL)) {
            String allCategory = (String) redisTemplate.opsForValue().get(RedisKey.KEY_MATERIAL_CATEGORY_ALL);
            listVo = JSONObject.parseArray(allCategory,MaterialCategoryVo.class);
        } else {
            List<BsMaterialCategory> list = bsMaterialCategoryBiz.findAllMaterialCategory();
            for (BsMaterialCategory category : list) {
                if (category.getLevel() == 1) {
                    MaterialCategoryVo vo = transformEntity2Vo(category);
                    for (BsMaterialCategory categoryTwo : list) {
                        if (categoryTwo.getLevel() == 2 && categoryTwo.getParentId().equals(vo.getId())) {
                            if (vo.getChildrens() == null) {
                                vo.setChildrens(new ArrayList<>());
                            }
                            MaterialCategoryVo voTwo = transformEntity2Vo(categoryTwo);
                            for (BsMaterialCategory categoryThree : list) {
                                if (categoryThree.getLevel() == 3 && categoryThree.getParentId().equals(categoryTwo.getId())) {
                                    if (voTwo.getChildrens() == null) {
                                        voTwo.setChildrens(new ArrayList<>());
                                    }
                                    MaterialCategoryVo voThree = transformEntity2Vo(categoryThree);
                                    voTwo.getChildrens().add(voThree);
                                }
                            }
                            if (voTwo.getChildrens() != null && voTwo.getChildrens().size() != 0) {
                                vo.getChildrens().add(voTwo);
                            }
//                            if(isHasThird){
//                                //vo.getChildrens().remove(voTwo);
//                                vo.getChildrens().add(voTwo);
//                            }
                        }
                    }
                    if (vo.getChildrens() != null && vo.getChildrens().size() != 0) {
                        listVo.add(vo);
                    }
//                    if(!isHasThird){
//                        listVo.remove(vo);
//                    }
                }
            }
            redisTemplate.opsForValue().set(RedisKey.KEY_MATERIAL_CATEGORY_ALL,JSONObject.toJSONString(listVo));
        }
        result.setData(listVo);
        return result;
    }

    @RequestMapping(value = "/findByLevel/anon", method = RequestMethod.GET)
    public RestResponse findByLevel(){
        RestResponse result = new RestResponse();
        List<MaterialCategoryVo> listVo = new ArrayList<>();

        //查询所有已经启用的货品种类信息 目前只有两级后期改为递归
        if (redisTemplate.hasKey(RedisKey.KEY_MATERIAL_CATEGORY_LEVEL)) {
            String allCategory = (String) redisTemplate.opsForValue().get(RedisKey.KEY_MATERIAL_CATEGORY_LEVEL);
            listVo = JSONObject.parseArray(allCategory,MaterialCategoryVo.class);
        } else {
            List<BsMaterialCategory> list = bsMaterialCategoryBiz.findByLevel();
            for (BsMaterialCategory category : list) {
                if (category.getLevel() == 2) {
                    MaterialCategoryVo vo = transformEntity2Vo(category);
                    for (BsMaterialCategory categoryOne : list) {
                        if (categoryOne.getLevel() == 3 && categoryOne.getParentId().equals(vo.getId())) {
                            if (vo.getChildrens() == null) {
                                vo.setChildrens(new ArrayList<>());
                            }
                            MaterialCategoryVo voOne = transformEntity2Vo(categoryOne);
                            vo.getChildrens().add(voOne);
                        }
                    }
                    if(vo.getChildrens() != null && vo.getChildrens().size() != 0){
                        listVo.add(vo);
                    }
                }
            }
            redisTemplate.opsForValue().set(RedisKey.KEY_MATERIAL_CATEGORY_LEVEL,JSONObject.toJSONString(listVo));
        }
        result.setData(listVo);
        return result;
    }

    public MaterialCategoryVo transformEntity2Vo (BsMaterialCategory bsMaterialCategory) {
        MaterialCategoryVo vo =  new MaterialCategoryVo();
        vo.setId(bsMaterialCategory.getId());
        vo.setCategoryName(bsMaterialCategory.getCategoryName());
        vo.setEnName(bsMaterialCategory.getEnName());
        vo.setLevel(bsMaterialCategory.getLevel());
        vo.setParentId(bsMaterialCategory.getParentId());
        vo.setSeqNum(bsMaterialCategory.getSeqNum());
        return vo;
    }

    @RequestMapping("/om/materiaList")
    public  RestResponse materialList(@RequestBody Map params){
        Page<BsMaterialCategory> data = bsMaterialCategoryBiz.findMaterialCategoryByCondition(params);
        Map reData = new HashMap();
        reData.put("total",data.getTotal());
        reData.put("rows",data.getResult());
        return RestResponse.success(reData);
    }

    /**
     * @Description: 获取一级、二级货品列表
     */
    @GetMapping("materialLevelList")
    public RestResponse<HashMap<Object, Object>> selectMaterialLevelList() {
    	List<RespMaterialCategoryLeveVo> lists = bsMaterialCategoryBiz.selectMaterialLevelList();
    	
    	HashMap<Object, Object> hashMap = new HashMap<>();
    	hashMap.put("materialLevel", lists);
    	
    	return RestResponse.success(hashMap);
    }

    /**
     * @Description: 获取货品列表
     */
    @GetMapping("materialList")
    public RestResponse<HashMap<Object, Object>> selectMaterialList(@Validated MaterialCategoryForm form) {
    	
    	HashMap<Object, Object> hashMap = bsMaterialCategoryBiz.selectMaterialList(form);

    	return RestResponse.success(hashMap);
    }

    /**
     * @Description: 更新货品启用/禁用状态
     */
    @GetMapping("updateStatus")
    public RestResponse<String> updateMaterialDisableStatus(@RequestParam(value = "id", required = true)Long id, @RequestParam(value = "disableStatus", required = true) Integer disableStatus) {
    	
    	if (DisableStatus.STATUS_DISABLE != disableStatus && DisableStatus.STATUS_ENABLE != disableStatus) {
    		return RestResponse.caughtException("参数有误");
    	}
		
		BsMaterialCategory materialCategory = bsMaterialCategoryBiz.selectMaterialById(id);
		
		if (materialCategory == null) {
			return RestResponse.success("无操作数据");
		}
		int maxLevel = bsMaterialCategoryBiz.selectMaterialMaxLevel();
		bsMaterialCategoryBiz.updateMaterialCategory(id, disableStatus, materialCategory, maxLevel);
		
    	return RestResponse.success("SUCCESS");
    }

    /**
     * 
     * @Description: 获取货品详情
     */
    @GetMapping("materialDetail")
    public RestResponse<HashMap<Object, Object>> selectMaterialDetail(@RequestParam(value = "id", required = true)Long id) {
    	
    	HashMap<Object, Object> hashMap = bsMaterialCategoryBiz.selectMaterialDetail(id);
    	
    	return RestResponse.success(hashMap);
    }

    /**
     * 
     * @Description:修改/添加货品接口
     */
    @GetMapping("updateMaterial")
    public RestResponse<String> updateMaterial(Long parentId, String categoryName, Long id, Integer seqNum) {
    	bsMaterialCategoryBiz.updateMaterial(parentId, categoryName, id, seqNum);
		return RestResponse.success("操作成功");
    	
    }

}
